package cn.cycleif.config.satoken;

import cn.cycleif.app.service.MenuService;
import cn.cycleif.app.service.RoleService;
import cn.cycleif.app.service.UserService;
import cn.cycleif.entity.Menu;
import cn.cycleif.entity.Role;
import cn.cycleif.entity.User;
import cn.cycleif.util.R;
import cn.dev33.satoken.stp.StpInterface;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * &#064;Date: 24/06/19-21:22
 * &#064;Desc: sa-token 接口，提供权限列表和角色列表
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class StpInterfaceImpl implements StpInterface {

  private final MenuService menuService;
  private final RoleService roleService;
  private final UserService userService;

  @Override
  public List<String> getPermissionList(Object loginId, String loginType) {
    HashSet<String> set = new HashSet<>();
    // 查询用户角色
    Integer       userId = Integer.valueOf(String.valueOf(loginId));
    User          user   = userService.getById(userId);
    R<List<Role>> roles  = roleService.getRolesByUserId(userId);
    // 查询角色权限
    for (Role role : roles.getData()) {
      R<List<Menu>> menus = menuService.getMenusByRoleId(role.getId());
      for (Menu menu : menus.getData()) set.add(menu.getType());
    }
    List<Menu> menus = menuService.selectByRanks(user.getRanks());
    for (Menu menu : menus) set.add(menu.getType());
    List<String> list = set.stream().toList();
    log.debug("用户{}权限列表：{}", userId, list);
    return list;
  }

  @Override
  public List<String> getRoleList(Object loginId, String loginType) {
    Integer       userId = Integer.valueOf(String.valueOf(loginId));
    R<List<Role>> roles  = roleService.getRolesByUserId(userId);
    List<String>  list   = new ArrayList<>();
    for (Role role : roles.getData()) list.add(role.getName());
    System.out.println("用户角色列表" + list);
    return list;
  }

}
